<template>
  <div>
    <div class="my-list-header">
      <div class="title">{{ whoseHomepage }}的提问</div>
    </div>
    <div class="custom-table p-x-16">
      <component-issues-list-item v-for="item in issues" :key="item.id" :issue="item" />
    </div>
    <window-bottom-load
      :loading="loading"
      :no-more="!nextPage"
      @load="loadIssues"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { formatIssues } from '@/views/issues/format';
import ComponentIssuesListItem from '@/views/users/show/lists/collections-list/component-issues-list-item';
import WindowBottomLoad from '@/components/window-bottom-load';

export default {
  name: 'issues-list',
  components: {
    ComponentIssuesListItem,
    WindowBottomLoad,
  },
  props: {
    curTab: String,
  },
  data() {
    return {
      issues: [],
      loading: false,
      nextPage: null,
    };
  },
  computed: {
    ...mapGetters(['whoseHomepage']),
    loadIssuesParams() {
      return {
        type: 'issues',
        userId: this.$route.params.userId,
        page: this.nextPage || 1,
      };
    },
    loadIssuesTriggerParams() {
      return {
        curTab: this.curTab, // this=issues
        userId: this.userId,
      };
    },
  },
  methods: {
    // 加载我的提问
    loadIssues() {
      this.loading = true;
      this.$api.users.myThings(this.loadIssuesParams)
        .then((res) => {
          this.issues = this.issues.concat(formatIssues(res.data));
          this.nextPage = res.kaminari.next_page;
        })
        .catch(() => {})
        .then(() => { this.loading = false; });
    },
    // 清空数据
    clearIssues() {
      this.issues = [];
      this.nextPage = null;
    },
  },
  watch: {
    loadIssuesTriggerParams(newVal, oldVal) {
      const userChanged = newVal.userId !== oldVal.userId; // 用户是否改变
      const isCurTab = newVal.curTab === 'issues'; // 是否激活当前类别
      const tabIntoCur = isCurTab && (oldVal.curTab !== 'issues'); // 从别的类型切换过来的
      const curNoData = !this.issues.length;

      if (userChanged) {
        this.clearIssues();
        if (isCurTab) {
          this.loadIssues(); // 如果在当前页面改变了用户
          return;
        }
      }

      if (tabIntoCur && curNoData) {
        this.loadIssues();
      }
    },
  },
};
</script>

<style></style>
